<?php

namespace app\admin\controller;

use app\admin\logic\CompanyLogic;
use app\admin\logic\CompanyUserLogic;
use app\admin\logic\crm\CrmSettingsLogic;
use app\admin\logic\crm\CustomersLogic;
use app\admin\logic\DealerLogic;
use app\admin\logic\MessageNotificationLogic;
use app\admin\logic\system\SystemDeptLogic;
use app\admin\logic\system\SystemUserLogic;
use app\common\logic\SystemRegionLogic;
use app\common\model\CrmFieldConfigs;
use app\common\service\SystemDictService;
use support\Request;
use support\Response;

/**
 * 不需要权限验证的控制器,用于获取基础信息
 */
class ApiController extends BaseController
{
    protected array $noNeedAuth = [
        'getRegion', 'getUserList', 
        'getFieldTypes', 'getFieldGroups', 
        'getValidationRules', 'getCustomerListFields',
        'getCustomerList',
    ];
    
    /**
     * 地区信息
     */
    public function getRegion(Request $request)
    {
        $regionLogic = new SystemRegionLogic();
        $where = $request->more([
            ['name', ''],
            ['parent_id', 0],
        ]);
        $isTree = $request->input('tree', 'false');
        if ($isTree === 'true') {
            unset($where['parent_id']);
            return $this->success($regionLogic->tree($where));
        }
        if (empty($where['parent_id'])) {
            $where['parent_id'] = 0;
        }
        $data = $regionLogic->getAllRegion($where);
        foreach($data as &$item) {
            if ($item['level'] < 4)
                $item['hasChildren'] = $regionLogic->search(['parent_id' => $item['id']])->count() > 0 ? 1 : 0;
            else
                $item['hasChildren'] = 0;
            
        }
        return $this->success($data);
    }
    
    /**
     * 用户列表
     * @param Request $request
     */
    public function getUserList(Request $request) {
        $where = $request->more([
            ['status', ''],
            ['dept_id', ''],
            ['post_id', ''],
            ['role_id', ''],
            ['username', ''],
        ]);
        if (empty($where['dept_id'])) {
            unset($where['dept_id']);
        }
        $page = $request->input('page', null);
        $limit = $request->input('limit', 10);
        $userLogic = new SystemUserLogic();
        $userList = $userLogic->search($where)->with(['depts' => function($query) {
            $query->field('id, name');
        }])->field('id, avatar, nickname, username, status, dept_id');
        if (!empty($page)) {
            $userList = $userList->paginate(['page' => $page, 'list_rows' => $limit]);
        } else {
            $userList = $userList->select();
        }
        return $this->success($userList->toArray());
    }
    

    /**
     * 获取字段类型枚举
     * @return Response
     */
    public function getFieldTypes(): Response
    {
        $types = \app\common\service\SystemDictService::getDictData('crm_field_type');

        // 如果字典中没有数据，使用默认配置
        if (empty($types)) {
            $types = [
                ['value' => 'text', 'label' => '文本框'],
                ['value' => 'textarea', 'label' => '多行文本'],
                ['value' => 'number', 'label' => '数字'],
                ['value' => 'select', 'label' => '下拉选择'],
                ['value' => 'checkbox', 'label' => '复选框'],
                ['value' => 'radio', 'label' => '单选框'],
                ['value' => 'date', 'label' => '日期'],
                ['value' => 'datetime', 'label' => '日期时间'],
                ['value' => 'region', 'label' => '地区选择'],
                ['value' => 'image', 'label' => '单图上传'],
                ['value' => 'images', 'label' => '多图上传'],
            ];
        }

        return $this->success($types);
    }

    /**
     * 获取分组及其字段树形结构
     * @param Request $request
     * @return Response
     */
    public function getFieldGroups(Request $request): Response
    {
        $logic = new CrmSettingsLogic();
        $groups = $logic->getGroupsWithFields();
        return $this->success($groups);
    }

    public function getValidationRules(Request $request) {
        $rules = SystemDictService::getDictData('validation_rule');
        return $this->success($rules);
    }

    /**
     * 获取后台显示的客户列表字段
     * @param Request $request
     * @return Response
     */

    public function getCustomerListFields(Request $request) {
        $fields = CrmFieldConfigs::whereNull('delete_time')
                ->order('group_id asc, sort asc')->select()->each(function ($item) {
                    return $item['options'] = !empty($item['options']) ? json_decode($item['options'], true) : [];
                })->toArray();
        
        return $this->success($fields);
    }

    public function getCustomerList(Request $request)
    {
        $params = $request->more([
            ['page', 1],
            ['limit', 20],
            ['name', ''],
            ['phone', ''],
            ['province_id', 0],
            ['city_id', 0],
            ['area_id', 0],
            ['stage', 0],
            ['id', 0]
        ]);
        $logic = new CustomersLogic();
        $result = $logic->getCustomerList($params, true);
        return $this->success($result);
    }
    
    public function getDeptList()
    {
        $deptLogic = new SystemDeptLogic();
        $deptList = $deptLogic->search()->field('id, name, parent_id')->select()->toArray();
        return $this->success($deptList);
    }

    public function getCompanyList()
    {
        $companyLogic = new CompanyLogic();
        $companyList = $companyLogic->search(['is_internal' => 0])->field('id, name, short_name')->select()->toArray();
        return $this->success($companyList);
    }

    public function getDealerList(Request $request)
    {
        $companyId = $request->input('company_id', 0);
        $where = [];
        $companyLogic = new CompanyLogic();
        $where = ['is_internal' => 0];
        if (!empty($companyId)) {
            $where['id'] = $companyId;
        }
        $companyIds = $companyLogic->search($where)->column('id');
        $dealerLogic = new DealerLogic();
        $dealerList = $dealerLogic->search()->whereIn('company_id', $companyIds)->field('id, name, short_name')->select()->toArray();
        return $this->success($dealerList);
    }
    
    public function getOperateNoticeType()
    {
        $typeLogic = new MessageNotificationLogic();
        $typeList = $typeLogic->getTypeList();
        return $this->success($typeList);
    }
    public function getCompanyUserRoleList(Request $request)
    {
        $companyId = $request->input('company_id', 0);
        $roleLogic = new CompanyUserLogic();
        $roleList = $roleLogic->getRoleList($companyId);
        return $this->success($roleList);
    }
}